########################################################################
# PLS 206 — Week 8 live coding, part 1: k-means clustering
# Grey Monroe, Fall 2026
########################################################################

# install.packages(c("ggplot2", "cluster"))
library(ggplot2)
library(cluster)

########################################################################
# Helpers (run this block once)
########################################################################

# simulate groups of samples around set means (one column per mean)
multinorm <- function(means, sds, n, name) {
  out <- data.frame(lapply(seq_along(means), function(i) rnorm(n, means[i], sds[i])))
  colnames(out) <- letters[seq_along(means)]
  out$group <- name
  out
}

# total within-cluster SS and average silhouette for k = 1 to kmax
choose_k <- function(x, kmax = 10) {
  d <- dist(x)
  out <- data.frame(k = 1:kmax, ss = NA, silhouette = NA)
  for (k in 1:kmax) {
    set.seed(1)
    km <- kmeans(x, centers = k, nstart = 25, iter.max = 50)
    out$ss[k] <- km$tot.withinss
    if (k > 1) out$silhouette[k] <- mean(silhouette(km$cluster, d)[, "sil_width"])
  }
  out
}

# the elbow and the silhouette side by side
plot_choose_k <- function(ck) {
  long <- rbind(data.frame(k = ck$k, value = ck$ss, what = "total within-cluster SS (elbow)"),
                data.frame(k = ck$k, value = ck$silhouette, what = "average silhouette (highest = best)"))
  ggplot(na.omit(long), aes(k, value)) +
    geom_line() + geom_point(size = 2.5) +
    facet_wrap(~what, scales = "free_y") +
    scale_x_continuous(breaks = ck$k) +
    labs(x = "k (number of clusters)", y = NULL) +
    theme_bw()
}

# renumber clusters from coldest (1) to warmest, so the numbers mean something
order_clusters <- function(cluster, temp) {
  o <- order(tapply(temp, cluster, mean))
  factor(match(cluster, o))
}

# map of the grid cells coloured by cluster
map_clusters <- function(data, cluster, title = NULL) {
  ggplot(data, aes(lon, lat, fill = cluster)) +
    geom_tile() +
    coord_quickmap() +
    scale_fill_brewer(palette = "RdYlBu", direction = -1, name = "cluster\n(coldest = 1)") +
    labs(x = "longitude (°)", y = "latitude (°)", title = title) +
    theme_bw()
}

########################################################################
# 1. k-means on 15 samples
########################################################################

set.seed(113)
mu <- rbind(c(2, 2), c(6, 3), c(4, 7))
pts <- data.frame(round(do.call(rbind, lapply(1:3, function(k) cbind(rnorm(5, mu[k, 1], 0.8), rnorm(5, mu[k, 2], 0.8)))), 2))
colnames(pts) <- c("v1", "v2")

ggplot(pts, aes(v1, v2)) +
  geom_point(size = 3) +
  labs(x = "variable 1", y = "variable 2") +
  theme_bw()

set.seed(1)
km <- kmeans(pts, centers = 3, nstart = 25)
km$cluster
km$centers
km$tot.withinss
# total within-cluster SS = 15.57

pts$cluster <- factor(km$cluster)
centres <- data.frame(km$centers, cluster = factor(1:3))
ggplot(pts, aes(v1, v2, colour = cluster)) +
  geom_point(size = 3) +
  geom_point(data = centres, shape = 23, size = 6, fill = "white", stroke = 1.5) +
  labs(x = "variable 1", y = "variable 2", colour = "cluster") +
  theme_bw()

# one random start at a time: some starts get stuck at a worse answer
ss_one_start <- sapply(1:25, function(s) {
  set.seed(s)
  kmeans(pts[, c("v1", "v2")], centers = 3, nstart = 1, algorithm = "Lloyd")$tot.withinss
})
round(ss_one_start, 1)
sum(abs(ss_one_start - min(ss_one_start)) < 1e-6)
# 13 of the 25 starts reach the lowest SS (15.57); the worst gets stuck at 64.6. nstart = 25 keeps the best.

########################################################################
# 2. Scale first
########################################################################

set.seed(1)
sim2 <- rbind(multinorm(c(1, 10), c(0.1, 1), 30, "group1"),
              multinorm(c(1.5, 10), c(0.1, 1), 30, "group2"))

set.seed(1)
ku <- kmeans(sim2[, c("a", "b")], centers = 2, nstart = 25)
table(ku$cluster, sim2$group)
# unscaled: each cluster is a mix of both groups (53% right, a coin flip)

set.seed(1)
ks <- kmeans(scale(sim2[, c("a", "b")]), centers = 2, nstart = 25)
table(ks$cluster, sim2$group)
# scaled: 100% right

sim2$unscaled <- factor(ku$cluster)
sim2$scaled <- factor(ks$cluster)
ggplot(sim2, aes(a, b, colour = scaled, shape = group)) +
  geom_point(size = 3) +
  labs(x = "a", y = "b", colour = "k-means cluster\n(scaled data)", shape = "true group") +
  theme_bw()

########################################################################
# 3. Choosing k
########################################################################

set.seed(2)
sim3 <- rbind(multinorm(c(12, 10), c(1, 1), 30, "group1"),
              multinorm(c(11, 15), c(1, 1), 30, "group2"),
              multinorm(c(7, 8), c(1, 1), 30, "group3"))

ck3 <- choose_k(scale(sim3[, c("a", "b")]))
ck3
plot_choose_k(ck3)
# elbow at k = 3; average silhouette highest at k = 3 (0.63)

# 10 variables, 4 hidden groups: no pair of variables shows them
set.seed(1)
sim10 <- do.call(rbind, lapply(1:4, function(g) multinorm(runif(10, 0, 3), rep(0.5, 10), 100, paste0("group", g))))
vars10 <- letters[1:10]

ggplot(sim10, aes(a, b)) +
  geom_point(alpha = 0.6) +
  theme_bw()

ck10 <- choose_k(scale(sim10[, vars10]))
plot_choose_k(ck10)
# elbow at k = 4; average silhouette highest at k = 4

set.seed(1)
km10 <- kmeans(scale(sim10[, vars10]), centers = 4, nstart = 25)
table(km10$cluster, sim10$group)
# every sample lands with its true group (100%)

pca10 <- prcomp(sim10[, vars10], scale. = TRUE)
summary(pca10)$importance[2, 1:3]
sim10$PC1 <- pca10$x[, 1]
sim10$PC2 <- pca10$x[, 2]
sim10$PC3 <- pca10$x[, 3]
sim10$cluster <- factor(km10$cluster)
ggplot(sim10, aes(PC1, PC2, colour = cluster, shape = group)) +
  geom_point(size = 2) +
  labs(x = "PC1 (34%)", y = "PC2 (21%)", colour = "k-means cluster", shape = "true group") +
  theme_bw()
# only three blobs: two of the groups overlap on PC1 and PC2

ggplot(sim10, aes(PC1, PC3, colour = cluster, shape = group)) +
  geom_point(size = 2) +
  labs(x = "PC1 (34%)", y = "PC3 (20%)", colour = "k-means cluster", shape = "true group") +
  theme_bw()
# on PC3 they split: k-means saw all 10 variables at once

########################################################################
# 4. Colombia: climate types from 19 variables
########################################################################

colombia <- read.csv("https://greymonroe.github.io/PLS_206/data/colombia_climate.csv")
str(colombia)
bio <- paste0("bio", 1:19)

ggplot(colombia, aes(lon, lat, fill = bio1)) +
  geom_tile() +
  coord_quickmap() +
  scale_fill_gradient2(low = "blue", mid = "lightyellow", high = "red", midpoint = 20, name = "mean temp (°C)") +
  labs(x = "longitude (°)", y = "latitude (°)") +
  theme_bw()

clim <- scale(colombia[, bio])

# k = 2
set.seed(1)
km2 <- kmeans(clim, centers = 2, nstart = 25, iter.max = 50)
colombia$k2 <- order_clusters(km2$cluster, colombia$bio1)
map_clusters(colombia, colombia$k2, "k = 2")
aggregate(cbind(bio1, bio12) ~ k2, data = colombia, FUN = mean)
# cool (16 °C, 597 cells) vs warm (26 °C, 2974 cells)

# how many clusters? (the silhouette takes a few seconds: 3571 cells)
ckc <- choose_k(clim)
ckc
plot_choose_k(ckc)
# no sharp elbow; silhouette best at k = 2 (0.43), runner-up k = 5 (0.37)

# k = 5
set.seed(1)
km5 <- kmeans(clim, centers = 5, nstart = 25, iter.max = 50)
colombia$k5 <- order_clusters(km5$cluster, colombia$bio1)
map_clusters(colombia, colombia$k5, "k = 5")
k5_means <- aggregate(cbind(bio1, bio12, bio15, lat, lon) ~ k5, data = colombia, FUN = mean)
k5_means$cells <- as.vector(table(colombia$k5))
k5_means[, -1] <- round(k5_means[, -1], 1)
k5_means
# 1: cool highlands, 15 °C. 2-5 all warm (25-27 °C), split by rain:
# 3 wettest (5557 mm, little seasonality, far west); 4 driest (1534 mm, seasonal, north);
# 2 wet all year (2950 mm, south); 5 seasonal (2677 mm, east)

ggplot(k5_means, aes(k5, bio12, fill = k5)) +
  geom_col() +
  scale_fill_brewer(palette = "RdYlBu", direction = -1, guide = "none") +
  labs(x = "cluster (coldest to warmest)", y = "annual rainfall (mm)") +
  theme_bw()

# k = 10, coldest to warmest
set.seed(1)
km10c <- kmeans(clim, centers = 10, nstart = 25, iter.max = 50)
colombia$k10 <- order_clusters(km10c$cluster, colombia$bio1)
ggplot(colombia, aes(lon, lat, fill = k10)) +
  geom_tile() +
  coord_quickmap() +
  scale_fill_manual(values = colorRampPalette(c("#313695", "#74ADD1", "#FEE090", "#A50026"))(10), name = "cluster\n(coldest = 1)") +
  labs(x = "longitude (°)", y = "latitude (°)") +
  theme_bw()
# cluster means run from 11 °C to 28 °C

# the clusters on a PCA of the same 19 variables
pca_c <- prcomp(colombia[, bio], scale. = TRUE)
summary(pca_c)$importance[2, 1:2]
colombia$PC1 <- pca_c$x[, 1]
colombia$PC2 <- pca_c$x[, 2]
cor(colombia$PC1, colombia$bio1)
cor(colombia$PC2, colombia$bio12)
ggplot(colombia, aes(PC1, PC2, colour = k5)) +
  geom_point(size = 1, alpha = 0.6) +
  scale_colour_brewer(palette = "RdYlBu", direction = -1, name = "cluster") +
  labs(x = "PC1 (45%): temperature", y = "PC2 (33%): rainfall") +
  theme_bw()
# PC1 tracks mean temperature (|r| = 0.96), PC2 annual rain (|r| = 0.87); the cool cluster stands apart
